﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ObjectFactory
{
    static Dictionary<string, List<GameObject>> objectPool = new Dictionary<string, List<GameObject>>();
    public static GameObject CreatBullet(string key,Action<GameObject> callBack)
    {
		string path="Bullet/"+key;
        return CreateObject(path,key,callBack);

    }
    public static GameObject CreatHpUI(string key,Action<GameObject> callBack)
    {
		string path="Prefabs/"+key;
        return CreateObject(path,key,callBack);

    }
    public static GameObject CreatEffect(string key, Action<GameObject> callBack)
    {
        string path = "VFx/" + key;
        return CreateObject(path, key, callBack);

    }
    private static GameObject CreateObject(string path,string key,Action<GameObject> callBack=null){


        GameObject o = FindObject(path,key);
        if (o==null)
        {
            o=InstantiateObj(path,key);
        }
        if (callBack != null)
        {
            callBack(o);
        }
        o.SetActive(true);
        return o;
    }

    private static GameObject FindObject(string path,string key)
    {
        if (!objectPool.ContainsKey(key))
        {
            List<GameObject> list = new List<GameObject>();
            GameObject obj1 = Resources.Load<GameObject>(path);
            GameObject inst = GameObject.Instantiate(obj1);
            list.Add(inst);
            objectPool.Add(key, list);
            return inst;
        }
        else
        {
            List<GameObject> objects = objectPool[key];
            int len = objects.Count;
            if (len > 0)
            {
                for (int i = 0; i < len; i++)
                {
                    GameObject o = objects[i];
                    if (!o.activeInHierarchy)
                    {
                        return o;
                    }
                }
            }
        }
        return null;
    }
	private static GameObject InstantiateObj(string path,string key){
			GameObject obj1 = Resources.Load<GameObject>(path);
			GameObject inst= GameObject.Instantiate(obj1);
        	objectPool[key].Add(inst);
			return inst;
	}





}
